import React, { useEffect, useRef, useState } from 'react';
import PageTitle from '@/components/PageTitle';
import { Button, Form, Input, message, Modal, Radio, Select } from 'antd';
import Tables from '@/hoc/Tables';
import Models from '@/components/Models';
import { Orignizers } from './index.d';
import styles from './index.less';
import { ENTRY_LIST } from '@/services/list';
import { BasicLayoutProps } from '@/layouts/BasicLayout';
import { connect } from 'umi';
import { ConnectState } from '@/models/connect';
import { delEntry, insertEntry, updateEntry } from '@/services/addliver';
import { TableProps } from '@/global.d';
import { queryAllUser } from '@/services/user';
import { getAuthority } from '@/utils/authority';
import { useData } from './hooks/index';
import { queryDefaultSelectedExhibition } from '@/services/institution';
import PageInfoSearch from '@/components/PageInfoSearch';

const { Option } = Select;

interface EntryProps extends BasicLayoutProps {
  userData: any;
}

const Entry: React.FC<EntryProps> = props => {
  const childRef = useRef<TableProps | any>();
  const title = props?.route?.name;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [issee, setIssee] = useState<boolean>(false);
  const [itemObj, setItemObj] = useState<any>({});
  const [userList, setUserList] = useState<any>([]);
  const [option, setOption] = useState<any>({});
  // 表格数据
  const [tableData, setTableData] = useState<any>({});
  // 初始化请求数据的 hooks
  const selectData: any = useData();
  // 默认选中的展览
  const [exhSelectedValue, setExhSelectedValue] = useState<number>();
  const [keyword, setKeyword] = useState<string>();

  // 单选的样式
  const radioStyle = {
    display: 'block',
    height: '30px',
    lineHeight: '30px',
    width: '200px',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  };

  /**
   * 表格的筛选
   * @param key
   */
  const getColumnSearchProps = (key: string) => ({
    filterDropdown: () => (
      <div className="totip">
        <div style={{ height: 200, overflow: 'auto' }}>
          <Radio.Group
            onChange={e => {
              const { value } = e.target;
              option[key] = value;
              setOption(() => ({
                ...option,
              }));
            }}
            value={option[key]}>
            {selectData[key]?.map((element: any, indexs: number) => (
              <Radio key={element?.id >= 0 || element?.id ? element?.id : `${indexs}_1231233123`} value={element?.id >= 0 || element?.id ? element.id : element} style={radioStyle}>
                <span title={element?.id >= 0 || element?.id ? element.exhibitionName : element}>{element?.id >= 0 || element?.id ? element.exhibitionName : element}</span>
              </Radio>
            ))}
          </Radio.Group>
        </div>

        <div className="totip_btn">
          <Button
            onClick={() => {
              option[key] = undefined;
              option.seach = 0;
              setOption(() => ({ ...option }));
              childRef.current.setQuery({});
            }}
            className="btn_cold">
            重置
          </Button>
          <Button
            onClick={() => {
              childRef.current.setQuery({
                exhibitionInfoId: option.fairSelectData,
                company: option.unitSelectData,
                status: option.statusData,
              });
              option.seach = 1;
              setOption(() => ({
                ...option,
              }));
            }}
            className="btn_red">
            查询
          </Button>
        </div>
      </div>
    ),
  });

  let { statusData } = selectData;

  // 表头
  let columns: any[] = [
    {
      title: '序号',
      key: 'key',
      width: 120,
      render: (_: any, record: any) => {
        return <div style={{ width: 80 }}>{record.idx}</div>;
      },
    },
    {
      title: '词条序号',
      dataIndex: 'orderNum',
      width: 120,
    },
    // {
    //   title: '参展展览',
    //   dataIndex: 'exhibitionName',
    //   key: 'exhibitionName',
    //   ...getColumnSearchProps('fairSelectData'),
    // },
    {
      title: '已选词条',
      dataIndex: 'entryName',
      key: 'entryName',
      align: 'left',
    },
    {
      title: '单位',
      dataIndex: 'company',
      key: 'company',
      align: 'left',
      ...getColumnSearchProps('unitSelectData'),
    },
    {
      title: '作者',
      dataIndex: 'userName',
      key: 'userName',
      align: 'left',
      ...getColumnSearchProps('writerArr'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: any) => <span>{statusData?.find((el: any) => el.id == status)?.exhibitionName ?? ''}</span>,
      ...getColumnSearchProps('statusData'),
    },
    {
      title: '操作',
      width: 250,
      render: (item: any) => (
        <div className="operation">
          <span
            onClick={() => {
              onEdit(item, 0);
            }}>
            查看
          </span>
          <span
            onClick={() => {
              onEdit(item, 1);
            }}>
            修改
          </span>
          <span
            onClick={() => {
              onisDis(item);
            }}>
            删除
          </span>
        </div>
      ),
    },
  ];
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  /**
   * 判断是否是作者权限
   */
  const rc = getAuthority();
  let isUser = rc == 'admin';
  /**
   * 添加展览
   */
  const onChange = () => {
    setVisible(true);
  };

  /**
   * 弹窗关闭
   */
  const handleCancel = () => {
    setVisible(false);
    setItemObj({});
    form.resetFields();
    setIssee(false);
  };

  /**
   * 查看
   * @param item
   */
  const onEdit = (item: Orignizers, id: number) => {
    setItemObj(item);
    form.setFieldsValue(item);
    if (!id) {
      setIssee(true);
    }

    onChange();
  };

  let arrayList: any[] = [
    // {
    //   name: '参展名称',
    //   value: 'exhibitionName',
    // },
    {
      name: '印面',
      value: 'printingSurface',
    },
    // {
    //   name: '已选词条',
    //   value: 'entryName',
    // },
    {
      name: '印顶/纽',
      value: 'imprinting',
    },
    {
      name: '边款一',
      value: 'frameA',
    },
    {
      name: '边款二',
      value: 'frameB',
    },

    {
      name: '边款三',
      value: 'frameC',
    },
    {
      name: '所属单位',
      value: 'company',
    },
    {
      name: '作者姓名',
      value: 'userId',
    },
    {
      name: '词条序号',
      value: 'orderNum',
    },
  ];

  /**
   * 保存
   * @param values
   */
  const onFinish = (values: any): void => {
    let value: any = {
      userId: props?.userData?.id,
      ...values,
      orderNum: values?.orderNum ? values.orderNum * 1 : null,
      id: itemObj?.id,
    };

    if (itemObj?.id) {
      updateEntry(value).then(res => {
        if (res?.responseCode == 200) {
          message.success('词条修改成功');
          handleCancel();
        }
      });
    } else {
      insertEntry(value).then(res => {
        if (res?.responseCode == 200) {
          message.success('词条保存成功');
          handleCancel();
        }
      });
    }
    childRef.current.setQuery({});
  };

  useEffect(() => {
    queryAllUser({}).then(res => {
      if (res?.responseCode == 200) {
        setUserList(res?.data);
      }
    });

    // 获取展览下拉列表默认选中的展览
    queryDefaultSelectedExhibition().then(resp => {
      if (resp?.responseCode == 200) {
        setExhSelectedValue(resp?.data);
      }
    });
  }, []);

  // 展览下拉列表选中的展览更改时触发刷新表格请求
  useEffect(() => {
    childRef.current.setQuery({
      exhibitionInfoId: exhSelectedValue,
    });
    option.seach = 1;
    setOption(() => ({
      ...option,
    }));
  }, [exhSelectedValue]);

  /**
   * 删除
   */
  const onisDis = (item: Orignizers) => {
    Modal.confirm({
      title: '删除提示',
      content: '确定要删除此条词条信息吗？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        delEntry({ id: item.id }).then((res: any) => {
          if (res?.responseCode == 200) {
            message.success('删除成功');
            childRef.current.setQuery({});
          } else {
            message.success('删除失败');
          }
        });
      },
    });
  };

  const onExhibitionSelected = (value: any) => {
    setExhSelectedValue(value);
  };

  const { totalCount } = tableData ?? {};

  return (
    <div className={styles.regimePage}>
      <PageTitle
        title={title}
        right={
          <Button className="btn_red" onClick={onChange}>
            添加词条
          </Button>
        }
      />
      <PageInfoSearch>
        <Select style={{ width: 300 }} allowClear={false} placeholder={'请选择展览名称'} value={exhSelectedValue} onChange={onExhibitionSelected}>
          {selectData['fairSelectData']?.map((el: any) => (
            <Option key={el.id} value={el.id}>
              {el.exhibitionName}
            </Option>
          ))}
        </Select>
        <Input style={{ marginLeft: 20, width: 280 }} onChange={e => setKeyword(e.target.value)} placeholder="请输入词条关键词" allowClear />
        <Button
          onClick={() => {
            childRef.current.setQuery({ exhibitionInfoId: exhSelectedValue });
          }}
          style={{ marginLeft: 20 }}
          className="btn_cold">
          查询
        </Button>
      </PageInfoSearch>

      <div className="regime_table">
        <Tables
          childRef={childRef}
          url={ENTRY_LIST}
          columns={columns}
          option={{ userId: props?.userData?.id, keyword }}
          footer={option.seach && totalCount ? () => <div className="footCount">{totalCount}</div> : false}
          getValue={(value: any) => {
            setTableData(value);
          }}
        />
      </div>
      <Models className="add_regimes" width="540px" visible={visible} handleCancel={handleCancel}>
        <Form labelAlign="left" {...layout} form={form} onFinish={onFinish} name="control-hooks">
          <div className="add_user">{issee ? '查看词条' : itemObj?.id ? '修改词条' : '新增词条'}</div>
          <div className="add_user_form">
            <Form.Item label="展览名称" name={'exhibitionId'} required={false}>
              <Select disabled={issee} size={'large'} className={'regime_inputs'} allowClear placeholder={'请选择展览名称'}>
                {selectData['fairSelectData']?.map(el => (
                  <Option key={el.id} value={el.id}>
                    {el.exhibitionName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            {arrayList?.map(el => (
              <div key={el.value + '2112_id_123123'}>
                {el.value == 'userId' ? (
                  issee || isUser ? (
                    <Form.Item label={el.name} name={el.value} required={false}>
                      <Select disabled={issee} size="large" className="regime_inputs" allowClear placeholder={`请输入${el.name}`}>
                        {userList.map((els: any, index: number) => (
                          <Option key={`${index}_2112_id_123123`} value={`${els.id}`}>
                            {els.userName}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  ) : null
                ) : (
                  <Form.Item label={el.name} name={el.value} required={false}>
                    <Input disabled={issee} size="large" className="regime_inputs" allowClear placeholder={`请输入${el.name}`} />
                  </Form.Item>
                )}
              </div>
            ))}
          </div>
          <div className="hr"></div>
          <div className="regime_btns">
            <Button className="btn_cold" onClick={handleCancel}>
              关闭
            </Button>
            {!issee ? (
              <Button className="btn_red" htmlType="submit">
                保存
              </Button>
            ) : null}
          </div>
        </Form>
      </Models>
    </div>
  );
};

export default connect(({ login }: ConnectState) => ({ userData: login.userData }))(Entry);
